# 1.导包
import xgboost as xgb
from sklearn.preprocessing import LabelEncoder  # 标签编码器
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
import pandas as pd

# 2.加载数据
df = pd.read_csv("红酒品质分类.csv")
print(df.head())

# 3.数据基本处理
# print(df.info())    # 没有缺失值、没有空值

# 3.1获取特征值和目标值
x_data = df.iloc[:, :-1]
y_data = df.iloc[:, -1]
# print(y_data.value_counts())  # 由于分类不是从0开始，我们要转换成从0开始的

# 3.2 将标签值转换成0开始的
encoder = LabelEncoder()
y_data = encoder.fit_transform(y_data)
print(y_data)

# 3.2 划分数据集
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, random_state=22)

# 4.特征工程
# 4.1 特征预处理
transformer = StandardScaler()
x_train = transformer.fit_transform(x_train)
x_test = transformer.transform(x_test)

# 5.模型构建
model = xgb.XGBClassifier(n_estimators=25, max_depth=15, random_state=928, objective="multi:softmax")
model1 = xgb.XGBRegressor(n_estimators=25, max_depth=15, random_state=928, objective="multi:softmax")
model.fit(x_train, y_train)
print(model.score(x_test, y_test))

# 5.1 交叉验证和网格搜索
# 交叉验证
# model1 = xgb.XGBClassifier()
# param_dict={
#     "n_estimators": [i*5 for i in range(1, 21)],
#     "max_depth": [i*5 for i in range(1, 11)],
#     "random_state": [928],
#     "objective": ["multi:softmax"]
# }
# model1 = GridSearchCV(estimator=model1, param_grid=param_dict, cv=4)
# model1.fit(x_train, y_train)
# print(model1.score(x_test,y_test))
# print(model1.best_params_)
# 6.模型评估
